package cn.xiehang.SoundSight;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.progressindicator.CircularProgressIndicator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AllOrderFragment extends Fragment implements OrderAdapter.OnCancelOrderListener {
    TextView allOrderTextView,waitPayTextView,waitReceiveTextView,waitEvaluateTextView,finishTextView;
    RecyclerView recyclerView;
    String URL= SeverURL.URL+"/get_orders";
    private String cancelURL=SeverURL.URL+"/cancel_order";
    private String confirmURL=SeverURL.URL+"/confirm_order";
    private String evaluateURL=SeverURL.URL+"/evaluate_order";
    List<Order> orderList;
    CircularProgressIndicator progressIndicator;
    String status="全部";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_all_order, container, false);

        initViews(view);
        initData1();
        bindingEvents();


        return view;
    }

    private void bindingEvents() {
        allOrderTextView.setOnClickListener(v -> filterOrders("全部"));
        waitPayTextView.setOnClickListener(v -> filterOrders("待支付"));
        waitReceiveTextView.setOnClickListener(v -> filterOrders("待收货"));
        waitEvaluateTextView.setOnClickListener(v -> filterOrders("待评价"));
        finishTextView.setOnClickListener(v -> filterOrders("已完成"));
    }
    private void filterOrders(String status) {
        this.status=status;
        // 过滤订单列表
        List<Order> filteredOrders = new ArrayList<>();
        for (Order order : orderList) {
            if (status.equals("全部") || order.getOrderStatus().equals(status)) {
                filteredOrders.add(order);
            }
        }
        // 更新RecyclerView
        OrderAdapter orderAdapter = new OrderAdapter(filteredOrders);
        orderAdapter.setCancelOrderListener(this);
        recyclerView.setAdapter(orderAdapter);
        orderAdapter.notifyDataSetChanged();
        //放大加粗对应的TextView
        switch (status) {
            case "全部":
                allOrderTextView.setTextSize(24);
                waitPayTextView.setTextSize(20);
                waitReceiveTextView.setTextSize(20);
                waitEvaluateTextView.setTextSize(20);
                finishTextView.setTextSize(20);
                break;
            case "待支付":
                allOrderTextView.setTextSize(20);
                waitPayTextView.setTextSize(24);
                waitReceiveTextView.setTextSize(20);
                waitEvaluateTextView.setTextSize(20);
                finishTextView.setTextSize(20);
                break;
            case "待收货":
                allOrderTextView.setTextSize(20);
                waitPayTextView.setTextSize(20);
                waitReceiveTextView.setTextSize(24);
                waitEvaluateTextView.setTextSize(20);
                finishTextView.setTextSize(20);
                break;
            case "待评价":
                allOrderTextView.setTextSize(20);
                waitPayTextView.setTextSize(20);
                waitReceiveTextView.setTextSize(20);
                waitEvaluateTextView.setTextSize(24);
                finishTextView.setTextSize(20);
                break;
            case "已完成":
                allOrderTextView.setTextSize(20);
                waitPayTextView.setTextSize(20);
                waitReceiveTextView.setTextSize(20);
                waitEvaluateTextView.setTextSize(20);
                finishTextView.setTextSize(24);
                break;
        }
        SetGoneProgressIndicator();
    }
    public void reClick(String status) {
        if (orderList == null) {
            return;
        }
        if (recyclerView == null) return;
        // 过滤订单列表
        initData(status);
    }

    private void initViews(View view) {
        // 初始化视图组件
        allOrderTextView = view.findViewById(R.id.all_order_fragment);
        waitPayTextView = view.findViewById(R.id.wait_pay_order_fragment);
        waitReceiveTextView = view.findViewById(R.id.wait_goods_order_fragment);
        waitEvaluateTextView = view.findViewById(R.id.wait_evaluate_order_fragment);
        finishTextView = view.findViewById(R.id.finish_order_fragment);
        recyclerView = view.findViewById(R.id.all_order_fragment_recycler_view);
        progressIndicator = view.findViewById(R.id.order_progressIndicator);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    }
    public void initData1() {
        initData("全部"); // 调用重载方法，传入默认值
    }

    public void initData(String status) {
        // 显示进度条
        progressIndicator.setVisibility(View.VISIBLE);
        // 设置RecyclerView不可见
        recyclerView.setVisibility(View.GONE);
        // 初始化数据
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return ;
        }
        String username = sharedPref.getString("username", null);
        String password = sharedPref.getString("password", null);
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("username", username);
            jsonBody.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 构建 RequestBody
        RequestBody requestBody = RequestBody.create(
                jsonBody.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );
        // 创建请求
        Request request = new Request.Builder()
                .url(URL)
                .post(requestBody)
                .addHeader("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 处理请求失败情况
                requireActivity().runOnUiThread(() -> {
                    AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                    builder.setTitle("订单列表出错")
                            .setMessage("error: " + e.getMessage())
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 关闭对话框
                                dialog.dismiss();
                            })
                            .show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                String responseData = response.body().string();

                try {
                    // 解析JSON数据
                    JSONObject jsonObject = new JSONObject(responseData);
                    JSONArray ordersArray = jsonObject.getJSONArray("orders");
                    orderList = new ArrayList<>();
                    for (int i = 0; i < ordersArray.length(); i++) {
                        JSONObject orderJson = ordersArray.getJSONObject(i);
                        String orderId = orderJson.getString("订单ID");
                        String orderStatus = orderJson.getString("订单状态");
                        String orderCreateTime = orderJson.getString("创建订单时间");
                        float totalPrice = (float) orderJson.getDouble("订单总金额");
                        float orderRating = (float) orderJson.optDouble("订单评分", 0.0); // 默认值为0.0
                        JSONArray productsArray = orderJson.getJSONArray("商品列表");
                        List<Product> productsList = new ArrayList<>();

                        for (int j = 0; j < productsArray.length(); j++) {
                            JSONObject productJson = productsArray.getJSONObject(j);
                            int id = productJson.getInt("商品ID");
                            String name = productJson.getString("商品名称");
                            String description = productJson.getString("商品介绍");
                            double price = productJson.getDouble("商品价格");
                            String image = productJson.isNull("商品图片") ? null : productJson.getString("商品图片");
                            int BuyCount = productJson.getInt("商品数量");

                            Product product = new Product(id, name, price, image, description);
                            product.setBuyCount(BuyCount);
                            productsList.add(product);
                        }
                        Order order = new Order(orderId, productsList, orderStatus, orderCreateTime, totalPrice);
                        order.setRating(orderRating);
                        orderList.add(order);
                    }
                    // 2. 所有数据解析完成后，一次性更新UI
                    requireActivity().runOnUiThread(() -> {

                        filterOrders(status); // 过滤订单列表

                        // 隐藏进度条

                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                    requireActivity().runOnUiThread(() -> {
                        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                        builder.setTitle("解析数据出错")
                                .setMessage("error: " + e.getMessage())
                                .setPositiveButton("确定", (dialog, which) -> {
                                    // 关闭对话框
                                    dialog.dismiss();
                                })
                                .show();
                    });
                }
            }
        });

    }
    public void SetGoneProgressIndicator() {

        // 设置进度指示器不可见
        requireActivity().runOnUiThread(() -> {
            progressIndicator.setVisibility(View.GONE);
            // 设置RecyclerView可见
            recyclerView.setVisibility(View.VISIBLE);
        });
    }

    public  void cancel_order(String orderId) {
        // 取消订单逻辑
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return ;
        }
        String username = sharedPref.getString("username", null);
        String password = sharedPref.getString("password", null);
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("username", username);
            jsonBody.put("password", password);
            jsonBody.put("orderID", orderId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 构建 RequestBody
        RequestBody requestBody = RequestBody.create(
                jsonBody.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );
        // 创建请求
        Request request = new Request.Builder()
                .url(cancelURL)
                .post(requestBody)
                .addHeader("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 处理请求失败情况
                requireActivity().runOnUiThread(() -> {
                    AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                    builder.setTitle("取消订单出错")
                            .setMessage("error: " + e.getMessage())
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 关闭对话框
                                dialog.dismiss();
                            })
                            .show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                String responseData = response.body().string();

                try {
                   //如果返回的json数据中包含'message': '订单取消成功'字段，则表示取消订单成功
                    JSONObject jsonObject = new JSONObject(responseData);
                    String message = jsonObject.getString("message");
                    boolean success = false;
                    if (message.equals("订单取消成功")) {
                        success = true;
                    } else {
                        success = false;
                    }
                    if (success) {

                        // 取消订单成功，更新UI
                        requireActivity().runOnUiThread(() -> {
                            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                            builder.setTitle("提示")
                                    .setMessage("取消订单成功")
                                    .setPositiveButton("确定", (dialog, which) -> {
                                        // 关闭对话框
                                        dialog.dismiss();
                                    })
                                    .show();
                        });
                        // 从订单列表中删除该订单
                        for (int i = 0; i < orderList.size(); i++) {
                            if (orderList.get(i).getOrderId().equals(orderId)) {
                                orderList.remove(i);
                                break;
                            }
                        }

                    } else {
                        // 取消订单失败，更新UI
                        requireActivity().runOnUiThread(() -> {
                            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                            builder.setTitle("提示")
                                    .setMessage("取消订单失败")
                                    .setPositiveButton("确定", (dialog, which) -> {
                                        // 关闭对话框
                                        dialog.dismiss();
                                    })
                                    .show();
                        });
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    requireActivity().runOnUiThread(() -> {
                        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                        builder.setTitle("解析数据出错")
                                .setMessage("error: " + e.getMessage())
                                .setPositiveButton("确定", (dialog, which) -> {
                                    // 关闭对话框
                                    dialog.dismiss();
                                })
                                .show();
                    });
                }
            }
        });
        this.initData(status); // 重新加载数据
    }
    private void confirm_order(String orderId) {
        // 确认订单逻辑
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return ;
        }
        String username = sharedPref.getString("username", null);
        String password = sharedPref.getString("password", null);
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("username", username);
            jsonBody.put("password", password);
            jsonBody.put("orderID", orderId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 构建 RequestBody
        RequestBody requestBody = RequestBody.create(
                jsonBody.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );
        // 创建请求
        Request request = new Request.Builder()
                .url(confirmURL)
                .post(requestBody)
                .addHeader("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 处理请求失败情况
                requireActivity().runOnUiThread(() -> {
                    AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                    builder.setTitle("确认收货出错")
                            .setMessage("error: " + e.getMessage())
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 关闭对话框
                                dialog.dismiss();
                            })
                            .show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                String responseData = response.body().string();

                try {
                    //如果返回的json数据中包含'message': '订单取消成功'字段，则表示取消订单成功
                    JSONObject jsonObject = new JSONObject(responseData);
                    String message = jsonObject.getString("message");
                    boolean success = false;
                    if (message.equals("确认收货成功")) {
                        success = true;
                    } else {
                        success = false;
                    }
                    if (success) {

                        // 取消订单成功，更新UI
                        requireActivity().runOnUiThread(() -> {
                            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                            builder.setTitle("提示")
                                    .setMessage("确认收货成功")
                                    .setPositiveButton("确定", (dialog, which) -> {
                                        // 关闭对话框
                                        dialog.dismiss();
                                    })
                                    .show();
                        });
                    } else {
                        // 取消订单失败，更新UI
                        requireActivity().runOnUiThread(() -> {
                            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                            builder.setTitle("提示")
                                    .setMessage("确认收货失败")
                                    .setPositiveButton("确定", (dialog, which) -> {
                                        // 关闭对话框
                                        dialog.dismiss();
                                    })
                                    .show();
                        });
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    requireActivity().runOnUiThread(() -> {
                        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                        builder.setTitle("解析数据出错")
                                .setMessage("error: " + e.getMessage())
                                .setPositiveButton("确定", (dialog, which) -> {
                                    // 关闭对话框
                                    dialog.dismiss();
                                })
                                .show();
                    });
                }
            }
        });
        this.initData(status); // 重新加载数据
    }
    private void evaluate_order(String orderId, float rating) {
        // 确认订单逻辑
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return ;
        }
        String username = sharedPref.getString("username", null);
        String password = sharedPref.getString("password", null);
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("username", username);
            jsonBody.put("password", password);
            jsonBody.put("orderID", orderId);
            jsonBody.put("rating", rating);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 构建 RequestBody
        RequestBody requestBody = RequestBody.create(
                jsonBody.toString(),
                MediaType.parse("application/json; charset=utf-8")
        );
        // 创建请求
        Request request = new Request.Builder()
                .url(evaluateURL)
                .post(requestBody)
                .addHeader("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 处理请求失败情况
                requireActivity().runOnUiThread(() -> {
                    AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                    builder.setTitle("订单评价出错")
                            .setMessage("error: " + e.getMessage())
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 关闭对话框
                                dialog.dismiss();
                            })
                            .show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected code " + response);
                }

                String responseData = response.body().string();

                try {
                    //如果返回的json数据中包含'message': '订单取消成功'字段，则表示取消订单成功
                    JSONObject jsonObject = new JSONObject(responseData);
                    String message = jsonObject.getString("message");
                    boolean success = false;
                    if (message.equals("订单评价成功")) {
                        success = true;
                    } else {
                        success = false;
                    }
                    if (success) {

                        // 取消订单成功，更新UI
                        requireActivity().runOnUiThread(() -> {
                            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                            builder.setTitle("提示")
                                    .setMessage("订单评价成功成功")
                                    .setPositiveButton("确定", (dialog, which) -> {
                                        // 关闭对话框
                                        dialog.dismiss();
                                    })
                                    .show();
                        });
                    } else {
                        // 取消订单失败，更新UI
                        requireActivity().runOnUiThread(() -> {
                            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                            builder.setTitle("提示")
                                    .setMessage("订单评价失败失败")
                                    .setPositiveButton("确定", (dialog, which) -> {
                                        // 关闭对话框
                                        dialog.dismiss();
                                    })
                                    .show();
                        });
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    requireActivity().runOnUiThread(() -> {
                        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                        builder.setTitle("解析数据出错")
                                .setMessage("error: " + e.getMessage())
                                .setPositiveButton("确定", (dialog, which) -> {
                                    // 关闭对话框
                                    dialog.dismiss();
                                })
                                .show();
                    });
                }
            }
        });
        this.initData(status); // 重新加载数据
    }

    @Override
    public void onCancelOrder(String orderId) {
        cancel_order(orderId);
    }

    @Override
    public void onConfirmOrder(String orderId) {
        confirm_order(orderId);
    }

    @Override
    public void onEvaluateOrder(String orderId) {
        // 评价订单逻辑
        // 这里可以弹出一个评价的对话框，用户输入评价内容
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setView(R.layout.dialog_rating) // 自定义布局
                .setPositiveButton("确定", (dialog, which) -> {
                    // 获取用户输入的评分
                    // 这里需要获取自定义布局中的 EditText 的值
                    EditText editText = ((AlertDialog) dialog).findViewById(R.id.rating_edit_text);
                    String rating = editText.getText().toString();
                    float ratingValue = Float.parseFloat(rating);
                    // 这里可以将评分发送到服务器
                    evaluate_order(orderId, ratingValue);

                    // 关闭对话框
                    dialog.dismiss();
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    // 关闭对话框
                    dialog.dismiss();
                })
                .show();
    }
}
